const Router = require('koa-router');
const jwt = require('jsonwebtoken');
const db = require('../db');

const router = new Router();
const SECRET_KEY = 'your_secret_key';

// 验证 token
const authenticateToken = (ctx, next) => {
    const authHeader = ctx.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];
    if (!token) return ctx.throw(401, '未授权');
    try {
        const decoded = jwt.verify(token, SECRET_KEY);
        ctx.user = decoded;
        return next();
    } catch (err) {
        return ctx.throw(403, 'Token 无效');
    }
};

// 获取待办事项
router.get('/', authenticateToken, async (ctx) => {
    db.all("SELECT * FROM todos WHERE user_id = ?", [ctx.user.id], (err, rows) => {
        if (err) {
            ctx.status = 500;
            ctx.body = { error: '数据库错误' };
            return;
        }
        ctx.body = rows;
    });
});

// 添加待办事项
router.post('/', authenticateToken, async (ctx) => {
    const { content } = ctx.request.body;
    db.run("INSERT INTO todos (user_id, content) VALUES (?, ?)", [ctx.user.id, content], function(err) {
        if (err) {
            ctx.status = 500;
            ctx.body = { error: '数据库错误' };
            return;
        }
        ctx.body = { id: this.lastID, content, status: 0 };
    });
});

// 更新待办事项
router.put('/:id', authenticateToken, async (ctx) => {
    const { content, status } = ctx.request.body;
    const { id } = ctx.params;
    db.run("UPDATE todos SET content = ?, status = ? WHERE id = ? AND user_id = ?", [content, status, id, ctx.user.id], (err) => {
        if (err) {
            ctx.status = 500;
            ctx.body = { error: '数据库错误' };
            return;
        }
        ctx.body = { message: "更新成功" };
    });
});

// 删除待办事项
router.delete('/:id', authenticateToken, async (ctx) => {
    const { id } = ctx.params;
    db.run("DELETE FROM todos WHERE id = ? AND user_id = ?", [id, ctx.user.id], (err) => {
        if (err) {
            ctx.status = 500;
            ctx.body = { error: '数据库错误' };
            return;
        }
        ctx.body = { message: "删除成功" };
    });
});

module.exports = router;
